const app = getApp();
import { getStorage, setStorage } from "../../../utils/localStorage"
import { myUserInfoUpdate, getUserInfo } from "../../../api/my"
import { getWePhoneNumber, ActivityRegistration } from "../../../api/homePage"
import { mediaPreView } from "../../../utils/util";
import { baseUrl } from "../../../api/request";
Page({
  data: {
    navData: {
      level: 2,
      title: '活动报名'
    },
    editFlag: true,
    baseUrl: baseUrl,
    //用户信息
    userInfo: {},
    imageList: [],
    url: baseUrl + '/common/upload',
    objDetail: {},
    yearArr: [],
    monthArr: [],
    dayArr: [],
    ageArr: [
      "0-20",
      "20-40",
      "40-60",
      "60-80",
      "80-100",
      "100-120",
    ],
    currentYear: null,
    currentMonth: null,
    agrentFlag: false,  //隐私协议状态
    navMargin: app.globalData.navHeight + app.globalData.navTop,
    //表单
    form: {}
  },
  onLoad(options) {
    if (JSON.stringify(options) != "{}") {
      let item = JSON.parse(decodeURIComponent(options.item));
      this.setData({
        objDetail: item,
        userInfo: getStorage("user"),
      });
      this.reset();
    } else {
      wx.showToast({
        title: '页面参数获取失败，请重新进入该页面',
        duration: 2000,
        icon: "none",
        mask: true,
      });
    };
  },
  onReady() {

  },
  onShow() {

  },

  //重置表单
  reset() {
    this.setData({
      form: {
        userId: this.data.userInfo.id,
        activityId: this.data.objDetail.id,
        realName: this.data.userInfo.realName || null,
        sex: this.data.userInfo.sex || null,
        phoneNumber: this.data.userInfo.phoneNumber || null,
        birthday: this.data.userInfo.birthday || null,
        team: this.data.userInfo.team || null,
      },
    });
  },
  //获取年月日
  getYmd() {
    const date = new Date()
    const years = []
    const months = []
    const days = []

    for (let i = 1920; i <= date.getFullYear(); i++) {
      years.push(i)
    };

    for (let i = 1; i <= 12; i++) {
      let index = i < 10 ? '0' + i : i;
      months.push(index)
    };

    for (let i = 1; i <= 31; i++) {
      let index = i < 10 ? '0' + i : i;
      days.push(index)
    };
    this.setData({
      yearArr: years,
      monthArr: months,
      dayArr: days,
    });
  },
  //真实姓名change事件
  realNameInput(e) {
    const value = e.detail.value;
    this.setData({
      "form.realName": value,
    });
  },

  //性别change事件
  sexChange(e) {
    let value = e.detail.value;
    this.setData({
      "form.sex": value,
    });
  },

  //手机号bindinput事件
  phoneInput(e) {
    const value = e.detail.value;
    this.setData({
      "form.phoneNumber": value,
    });
  },
  //生日srChange事件
  srChange(e) {
    let index = Number(e.detail.value);
    // let _this = this.data;
    // let idx = e.detail.value;
    // let year = _this.yearArr[idx[0]];
    // let month = _this.monthArr[idx[1]];
    // let day = _this.dayArr[idx[2]];
    this.setData({
      "form.birthday": this.data.ageArr[index],
    });
  },
  //团队bindinput事件
  teamInput(e) {
    const value = e.detail.value;
    this.setData({
      "form.team": value,
    });
  },

  //获取用户手机号
  getPhoneNumber(e) {
    if (e.detail.errMsg === "getPhoneNumber:ok") {
      getWePhoneNumber({ code: e.detail.code }).then(res => {
        if (res.data.code === 200) {
          this.getWxUser("phone");
        };
      });
    };
  },

  //获取用户信息
  getWxUser(type) {
    getUserInfo({ id: this.data.userInfo.id }).then(res => {
      if (res.data.code === 200) {
        res.data.data.username = res.data.data.userName;
        setStorage('user', res.data.data);
        type === "phone" ? this.setData({ "form.phoneNumber": res.data.data.phoneNumber }) : false;
      };
    });
  },

  //隐私协议checkbox按钮change事件
  ysxyClick(e) {
    let flag = e.detail.value.length === 0 ? false : true;
    this.setData({
      agrentFlag: flag
    });
  },
  //活动协议和隐私条款字体点击事件
  xieyiTap(e) {
    let index = e.currentTarget.dataset.index;
    if (index === 1) {
      wx.navigateTo({
        url: '/pagesWoDe/pages/service/index',
      });
    } else {
      wx.navigateTo({
        url: '/pagesWoDe/pages/policy/index',
      });
    };
  },
  //提交按钮点击事件
  async submit() {
    const _this = this.data;
    _this.agrentFlag ? this.activityApplication() : this.pageMessage("请先同意阅读了活动协议以及隐私条款");
  },

  //活动报名
  activityApplication() {
    const _this = this.data;
    if (_this.form.realName && _this.form.phoneNumber) {
      ActivityRegistration(_this.form).then(res => {
        if (res.data.code !== 200) return;
        this.pageMessage(res.data.msg);
        setTimeout(() => {
          var pages = getCurrentPages();
          var prevPage = pages[pages.length - 2]; //上一个页面
          prevPage.setData({
            mydata: {
              peopleNumber: this.data.objDetail.peopleNumber + 1,
              signUpState: res.data.data || true
            },
          })
          wx.navigateBack({//返回
            delta: 1
          });
          this.getWxUser();
        }, 2000);
      });
    } else {
      this.pageMessage("请输入真实姓名和手机号");
    };
  },

  /* 页面消息提示公用方法 */

  pageMessage(title, time) {
    wx.showToast({
      title: title,
      duration: time || 2000,
      icon: "none",
      mask: true,
      success: (res) => { },
      fail: (res) => { },
      complete: (res) => { },
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})